#!/bin/bash

export POWER_BTN_HIGH=0xFF
export POWER_BTN_LOW=0xFE
export RESET_BTN_HIGH=0xFF
export RESET_BTN_LOW=0xFD
export power_seq=( "$POWER_BTN_HIGH" "$POWER_BTN_LOW" "$POWER_BTN_HIGH" )
export reset_seq=( "$RESET_BTN_HIGH" "$RESET_BTN_LOW" "$RESET_BTN_HIGH")
export SERVICE="xyz.openbmc_project.Ipmi.Channel.Ipmb"
export OBJECT_PATH="/xyz/openbmc_project/Ipmi/Channel/Ipmb"
export INTERFACE="org.openbmc.Ipmb"
export DATA_LEN=0x05
export NETFN=0x06
export LUN=0x00
export CMD=0x52
export STATE_OFF=0
export STATE_ON=1
export STATE_UNKNOWN=-1
export CPLD_BUS_NUM=12
export CPLD_PWR_CTRL_ADDR=0xf
export POW_ON_SLOT=0x01
export POW_OFF_SLOT=0x00
export PWRGD_SYS_PWROK_INDEX=12
export IANA="0x15 0xA0 0x0"
export IANA_LEN=3
export CHASSIS_BUS_NAME="xyz.openbmc_project.State.Chassis"
export CHASSIS_OBJ_PATH="/xyz/openbmc_project/state/chassis"
export CHASSIS_INTF_NAME="xyz.openbmc_project.State.Chassis"
export CHASSIS_PROPERTY_NAME="CurrentPowerState"
export HOST_BUS_NAME="xyz.openbmc_project.State.Host"
export HOST_OBJ_PATH="/xyz/openbmc_project/state/host"
export HOST_INTF_NAME="xyz.openbmc_project.State.Host"
export HOST_PROPERTY_NAME="CurrentHostState"
export CHASSIS_ON="xyz.openbmc_project.State.Chassis.PowerState.On"
export CHASSIS_OFF="xyz.openbmc_project.State.Chassis.PowerState.Off"
export HOST_ON="xyz.openbmc_project.State.Host.HostState.Running"
export HOST_OFF="xyz.openbmc_project.State.Host.HostState.Off"
export IPMB_CMD_COMPLETE_CODE_INDEX=2

host-power-status()
{
    SLOT_ID=$1

    response="$(busctl call "$SERVICE" "$OBJECT_PATH" "$INTERFACE" sendRequest yyyyay "$SLOT_ID" 0x38 "$LUN" 0x03 0x03 0x15 0xa0 0x00)"
    result=$(echo "$response" | cut -d" " -f "$PWRGD_SYS_PWROK_INDEX")
    res="$(( "$result" & 0x80  ))"
    status="$(( "$res" >> 7 ))"

    echo "$status"
    return 0
}

chassis-power-status()
{
    slot=$1
    status=-1

    if [ "$slot" -le 4  ]
    then
            response="$(i2cget -y "$CPLD_BUS_NUM" "$CPLD_PWR_CTRL_ADDR" 0x25)"
            res="$(( "$response" >> slot ))"
            status="$(( "$res" & 0x01  ))"
    fi

    echo "$status"
    return 0
}
